package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyYouQianLai;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeYouQianLai;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 安心分期掩码出量有钱
 *
 * 链接: https://apifox.com/apidoc/shared-b104362f-c4e0-48e0-86a1-31aab174793a  访问密码: youqian
 *
 * @author WJB
 */
@ApiPlan(productId = "352", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatYouQianLaiPhoneMaskConvert implements ApiPlatformPhoneMaskConvertHandler {
    public static final String AES = "AES";
    public static final String AES_CBC_CIPHER = "AES/CBC/PKCS5Padding";
    public static final String KEY = "RBZ/udTtxNUws9N+vKVz+w==";
    public static final String CHANNEL_ID = "ngxeue";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        ApiPlatDataExchangeYouQianLai data = new ApiPlatDataExchangeYouQianLai();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        // 手机号8位
        data.setMobilePrefix8(apiDataExchangeParameter.getPhoneMask());
        // 年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别 0-女 1-男 默认1
        String sex = apiDataExchangeParameter.getSex();
        Integer sexChoose = ChooseEq.create()
                .when(sex, "0", 1)
                .when(sex, "1", 2)
                .end(1);
        data.setGender(sexChoose);
        //  城市
        data.setWorkCity(apiDataExchangeParameter.getCity());
        data.setWorkCityCode(apiDataExchangeParameter.getProvinceCode() + "," + apiDataExchangeParameter.getAreaCode());
        //  职业
        Integer job = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 10)
                .when(apiDataExchangeParameter.getCareer(), "2", 20)
                .when(apiDataExchangeParameter.getCareer(), "3", 30)
                .when(apiDataExchangeParameter.getCareer(), "4", 10)
                .when(apiDataExchangeParameter.getCareer(), "5", 20)
                .end(10);
        data.setJob(job);
        //  房产情况
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 0)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 1)
                .end(0);
        data.setHouseProperty(house);
        //  车产
        Integer car = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 0)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 1)
                .end(0);
        data.setCarProperty(car);
        //  社保
        Integer shebao = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 0)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 1)
                .end(0);
        data.setSocialSecurity(shebao);
        //  公积金
        Integer gongjijin = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 0)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 1)
                .end(0);
        data.setHousingFund(gongjijin);
        //  保单
        Integer baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 0)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 1)
                .end(0);
        data.setInsurance(baodanIs);
        // 信用记录
        Integer creditHistory = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", 0)
                .when(apiDataExchangeParameter.getOverdue(), "2", 1)
                .when(apiDataExchangeParameter.getOverdue(), "3", 1)
                .end(0);
        data.setCreditInvestigation(creditHistory);
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 4)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 5)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 3)
                .end(0);
        data.setSesameCredit(zhima);
        //  贷款金额
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 1)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 3)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 4)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 4)
                .end(1);
        data.setApplyLimit(money);
        //  收入情况
        Integer salaryPayMethod = ChooseEq.create()
                .when(apiDataExchangeParameter.getSalaryPayMethod(), "1", 2)
                .when(apiDataExchangeParameter.getSalaryPayMethod(), "2", 3)
                .when(apiDataExchangeParameter.getSalaryPayMethod(), "3", 1)
                .end(1);
        data.setPayoffForm(salaryPayMethod);

        String encrypt = encrypt(JsonUtils.toJson(data), KEY);
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("data", encrypt);
        });
        return JsonUtils.toJson(map);
    }

    /**
     * AES 加密 CBC模式
     *
     * @param data 需要加密的内容
     * @param key  密钥
     * @return 密文
     */
    public static String encrypt(String data, String key) {
        byte[] dataByteArray = data.getBytes(StandardCharsets.UTF_8);
        byte[] keyByteArray = java.util.Base64.getDecoder().decode(key);
        try {
            SecretKeySpec secretKey = new SecretKeySpec(keyByteArray, AES);
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, AES);
            Cipher cipher = Cipher.getInstance(AES_CBC_CIPHER);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(keyByteArray));
            byte[] valueByte = cipher.doFinal(dataByteArray);
            return java.util.Base64.getEncoder().encodeToString(valueByte);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) {
        ApiPlatApplyYouQianLai data = new ApiPlatApplyYouQianLai();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        // 手机号
        data.setMobile(apiApplyParameter.getPhone());
        data.setRealName(apiApplyParameter.getUserName());
        // 年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别 0-女 1-男 默认1
        String sex = apiApplyParameter.getSex();
        Integer sexChoose = ChooseEq.create()
                .when(sex, "0", 1)
                .when(sex, "1", 2)
                .end(1);
        data.setGender(sexChoose);
        //  城市
        data.setWorkCity(apiApplyParameter.getCity());
        data.setWorkCityCode(apiApplyParameter.getProvinceCode() + "," + apiApplyParameter.getAreaCode());
        //  职业
        Integer job = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 10)
                .when(apiApplyParameter.getCareer(), "2", 20)
                .when(apiApplyParameter.getCareer(), "3", 30)
                .when(apiApplyParameter.getCareer(), "4", 10)
                .when(apiApplyParameter.getCareer(), "5", 20)
                .end(10);
        data.setJob(job);
        //  房产情况
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 0)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 1)
                .end(0);
        data.setHouseProperty(house);
        //  车产
        Integer car = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 0)
                .when(apiApplyParameter.getCarInfo(), "2", 1)
                .when(apiApplyParameter.getCarInfo(), "3", 2)
                .when(apiApplyParameter.getCarInfo(), "4", 1)
                .end(0);
        data.setCarProperty(car);
        //  社保
        Integer shebao = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 0)
                .when(apiApplyParameter.getSocialSecurity(), "2", 1)
                .when(apiApplyParameter.getSocialSecurity(), "3", 2)
                .when(apiApplyParameter.getSocialSecurity(), "4", 1)
                .end(0);
        data.setSocialSecurity(shebao);
        //  公积金
        Integer gongjijin = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 0)
                .when(apiApplyParameter.getProvidentFund(), "2", 1)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 1)
                .end(0);
        data.setHousingFund(gongjijin);
        //  保单
        Integer baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 0)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 1)
                .end(0);
        data.setInsurance(baodanIs);
        // 信用记录
        Integer creditHistory = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", 0)
                .when(apiApplyParameter.getOverdue(), "2", 1)
                .when(apiApplyParameter.getOverdue(), "3", 1)
                .end(0);
        data.setCreditInvestigation(creditHistory);
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 4)
                .when(apiApplyParameter.getSesameCredit(), "2", 5)
                .when(apiApplyParameter.getSesameCredit(), "3", 2)
                .when(apiApplyParameter.getSesameCredit(), "4", 3)
                .end(0);
        data.setSesameCredit(zhima);
        //  贷款金额
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 1)
                .when(apiApplyParameter.getLoanAmount(), "2", 3)
                .when(apiApplyParameter.getLoanAmount(), "3", 4)
                .when(apiApplyParameter.getLoanAmount(), "4", 4)
                .end(1);
        data.setApplyLimit(money);
        //  收入情况
        Integer salaryPayMethod = ChooseEq.create()
                .when(apiApplyParameter.getSalaryPayMethod(), "1", 2)
                .when(apiApplyParameter.getSalaryPayMethod(), "2", 3)
                .when(apiApplyParameter.getSalaryPayMethod(), "3", 1)
                .end(1);
        data.setPayoffForm(salaryPayMethod);
        data.setIp(apiApplyParameter.getIp());
        //  授权协议
        ApiPlatApplyYouQianLai.Protocol protocol = new ApiPlatApplyYouQianLai.Protocol();
        protocol.setUrl(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
        List<ApiPlatApplyYouQianLai.Protocol> list = new ArrayList<>();
        list.add(protocol);
        data.setProtocolList(list);

        String encrypt = encrypt(JsonUtils.toJson(data), KEY);
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("data", encrypt);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();
        RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();
        BigDecimal price = resData.getBigDecimal("maxPrice");
        String companyName = resData.getString("companyName");
        String productName = resData.getString("productName");
        String logo = resData.getString("productLogo");

        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            //  获取协议
            JSONArray listProtocolResult = resData.getJSONArray("protocolList");
            IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
                JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                ApiProtocol protocol = new ApiProtocol();
                protocol.setProtocolName(protocolObject.getString("name"));
                protocol.setProtocolUrl(protocolObject.getString("url"));
                newList.add(protocol);
            });
        });

        List<String> phoneMd5List = CollUtils.newArrayList(newList -> {
            JSONArray jsonArray = resData.getJSONArray("md5List");
            IteratorUtils.array(jsonArray, (protocolResult, index) -> {
                String phoneMd5 = jsonArray.getString(index);
                newList.add(phoneMd5);
            });
        });

        result.setPrice(price);
        result.setLogoPath(logo);
        result.setDisplayName(companyName);
        result.setListPhoneMd5(phoneMd5List);
        result.setProductName(productName);
        result.setProtocolList(protocolList);
        listRespPlatformPhoneMaskDataExchange.add(result);
        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }

}
